package com.zh.yqbj.util;


import java.util.Objects;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;

import com.zh.yqbj.exception.accountExcption.NoMoneyException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信服务
 * 开发环境不启用
 */
@Slf4j
@Data
@Component
@ConfigurationProperties("aliyun.sms")
public class SMSUtil {

    private String smsAccessKeyId;
    private String smsAccessKeySecret;
    private String smsEndpoint;
    private String smsSignName;
    private String smsTemplateCode;

    /**
     * 初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    private Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = smsEndpoint;
        return new Client(config);
    }

    /**
     * 开发环境不启用
     * @param phone 目标手机号
     * @param code 验证码
     * @return
     */
    public boolean sendSms(String phone, int code) throws NoMoneyException {
        Client client;
        try {
            client = createClient(smsAccessKeyId, smsAccessKeySecret);
        } catch (Exception e) {
            log.error("发送短信,使用初始化账号Client异常, {}", e.getMessage());
            return false;
        }
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(smsSignName)
                .setTemplateCode(smsTemplateCode)
                .setTemplateParam("{\"code\":" + code + "}");
        SendSmsResponse resp;
        try {
            resp = client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("发送短信失败, {}", e.getMessage());
            return false;
        }
        if (resp == null || !Objects.equals(resp.getBody().getCode(), "OK")) {
            return false;
        }
        return true;
    }
}
